var express = require('express');
var router = express.Router();
var fs = require('fs');
var gm = require('gm');//处理图片
/*var BufferHelper = require('bufferhelper');
var xml2js = require('xml2js');*/

var randomString = require('random-string');//获取随机6位数字
var luosimao = require("../utils/luosimao");
/*var https = require('https');
var querystring = require('querystring');*/

var debug = require('debug')('index');
var crypto  = require('crypto');

//var db = require('../utils/dbConn');

//var Users = require("../models/users").Users;
var Page = require("../models/Page");
var LifeService = require('../models/LifeService').LifeService;
var LifeGoods = require('../models/LifeGoods').LifeGoods;
var Industry = require('../models/LifeGoods').Industry;
var City = require('../models/City').City;
var ServiceType = require('../models/ServiceType').ServiceType;
var UserLifeGoods = require('../models/LifeGoods').UserLifeGoods;//用户预定的生活服务
var Users = require('../models/LifeGoods').Users;
/* GET home page. */
router.get('/', function(req, res) {
    //var conn =null;
    /*
     db.getPool.getConnection(function(err, connection) {
     if(err){

     }else{
     connection.query('SELECT * FROM users',function(err,rows){
     db.release(connection);
     });
     }
     });
     */
//res.redirect('view/index.html');
    /* s(username, nickname, password, usertype, integral, activeid, did, createtime) {*/
    //var users = new Users('aa',"ss","12310",1,12,12,23,new Date()).save();

    //res.render('index', { title: 'Express' });
    //res.redirect('/login.html');
    res.render('login',{
        msg:''
    });
});

router.post('/lifeService/lifeServiceList', function(req, res, next) {
    /*var order = req.body.order;
     var page = req.body.page;
     var rows = req.body.rows;
     var sort = req.body.sort;*/

    var params = [req.body.busDate1,req.body.busDate2,req.body.busName,req.body.serv,req.body.cityid,req.body.servid,req.body.serv_id,req.body.recommend];//req.body.servid商家ID serv_id服务ID

    var page = [req.body.sort,req.body.order,(Number(req.body.page)-1)*Number(req.body.rows),Number(req.body.rows)];
    new LifeService().getList(params,page,function(result){
        res.send(result);
    });
    debug('生活服务列表');

});

/**
 * 添加商家
 */
router.post('/auth/lifeService/addBus', function(req,res){
    var users = {
        username:req.body.username,
        nickname:req.body.nickname,
        password:crypto.createHash('md5').update(req.body.password).digest('hex').toUpperCase(),
        phone:req.body.phone,
        email:req.body.email,
        createtime:new Date()
    }
    console.log(req.files.filePath.path);
    gm(req.files.filePath.path)
        .resize(280, 280,'!')//强制此宽高裁剪，不是1比1的话会拉伸，不加！号可保持纵横比
        .noProfile()
        .write(req.files.filePath.path+'1', function (err) {
            console.log(req.files.filePath.path+'1');
            if (!err){
                var bitFile = fs.readFileSync(req.files.filePath.path+'1');
                var pic = new Buffer(bitFile).toString('base64');
                fs.unlinkSync(req.files.filePath.path);//删除文件原
                fs.unlinkSync(req.files.filePath.path+'1');//删除裁剪后文件
                /*new LifeService(req.body.serv_id,req.body.lname,req.body.lprice,req.body.describe,req.body.tel,req.body.address,req.body.coords,pic,req.body.cid,new Date()).save(users,function(result){
                    res.setHeader('Content-Type','text/html');
                    res.send(result);
                });*/
                new LifeService(req.body.serv_id,req.body.lname,req.body.lprice,req.body.describe,req.body.tel,req.body.address,req.body.coords,pic,req.body.cid,new Date(),req.body.recommend).save(users,function(result){
                    res.setHeader('Content-Type','text/html');
                    res.send(result);
                });
            }
        });

});

/**
 * 编辑商家信息
 */
router.post('/auth/lifeService/editBus', function(req,res){
console.log(req.files);

    gm(req.files.filePath.path)
        .resize(280, 280,'!')//强制此宽高裁剪，不是1比1的话会拉伸，不加！号可保持纵横比
        .noProfile()
        .write(req.files.filePath.path+'1', function (err) {
            console.log(req.files.filePath.path+'1');
            if (!err){
                var bitFile = fs.readFileSync(req.files.filePath.path+'1');
                var pic = new Buffer(bitFile).toString('base64');
                fs.unlinkSync(req.files.filePath.path);//删除文件
                fs.unlinkSync(req.files.filePath.path+'1');//删除裁剪后文件
                var lifeService = new LifeService(Number(req.body.serv_id),req.body.lname,req.body.lprice,req.body.describe,req.body.tel,req.body.address,req.body.coords,pic,Number(req.body.cid),new Date(req.body.createtime),req.body.recommend);
                lifeService.lid = req.body.lid;
                lifeService.update(function(result){
                    res.setHeader('Content-Type','text/html')
                    res.send(result);
                });
            }
        });


});

/**
 * 删除选中的商家
 */
router.post('/auth/lifeService/delBus', function(req,res){
    var ids = req.body['ids'];
    new LifeService().delBus(ids,function(result){
        res.send(result);
    });
});

/**
 * 城市列表
 */
router.get('/getCityList',function(req,res){
    new City().getCityList(function(result){
        res.send(result);
    });
});

/**
 * 服务列表
 */
router.get('/lifeService/getServiceTypeList',function(req,res){
    new ServiceType().getServiceTypeList(function(result){
        res.send(result);
    });
});

router.post('/lifeService/serviceType/list', function(req, res){
    new ServiceType().list(req.body, function(data){
        res.send(data);
    })

});
router.post('/auth/lifeService/serviceType/edit', function(req, res){
    new ServiceType().edit(req.body, function(data){
        res.setHeader('Content-Type','text/html');
        res.send(data);
    })

});
router.post('/auth/lifeService/serviceType/add', function(req, res){
    new ServiceType().add(req.body, function(data){
        res.setHeader('Content-Type','text/html');
        res.send(data);
    })

})
router.post('/auth/lifeService/serviceType/del', function(req, res){
    new ServiceType().del(req.body.ids, function(data){
        res.setHeader('Content-Type','text/html');
        res.send(data);
    })
})
router.post('/lifeService/serviceType/predel', function(req, res){
    new ServiceType().predel(req.body.ids, function(data){
        res.setHeader('Content-Type','text/html');
        res.send(data);
    })
})
/*<<<<<<< HEAD
router.post('/userManage/userList',function(req, res, next){
    //console.log
    new Users().list(function(userList){
        res.send(userList);
    })
});
=======
>>>>>>> 65021f7862a2f0558ec893ac76ec637f0d26a805*/

router.post('/lifeService/lifeServiceGoodsList', function(req, res) {
    var params = [req.body.bgDate1,req.body.bgDate2,req.body.bgName,req.body.servid];

    var page = [req.body.sort,req.body.order,(Number(req.body.page)-1)*Number(req.body.rows),Number(req.body.rows)];
    new LifeGoods().getList(params,page,function(result){
        res.send(result);
    });
    debug('生活服务商品列表');

});

/**
 * 获取某城市内商家列表
 */
router.get('/lifeService/getBusListByCity', function(req, res){
    debug('城市ID'+req.query.cid);
    new LifeGoods().getBusListByCity(req.query.cid, function(result){
        res.send(result);
    });
});

/**
 * 添加商品类型
 */
router.post('/auth/lifeService/addIndustry',function(req, res){
    //console.log(req.body+'----------------------------------------');
    debug('添加商品类型');
    new Industry(req.body.industry, req.body.sid, req.body.describe).saveIndustry(function(result){
        res.setHeader('Content-Type','text/html');//防止浏览器下载
        res.send(result);
    });

});

router.get('/lifeService/getSyList',function(req, res){
    debug('商品类型列表');
    new Industry().getSyList(req.query.sid, function(result){
        res.send(result);
    });

});

/**
 * 添加产品
 */
router.post('/auth/lifeService/addBusGoods', function(req,res){
    console.log(req.body.coords);
    var coords = req.body.coords;
    var imgPathOfBus = 'images/busimgs/bus'+req.body.lid;//根据产品ID创建目录
    if(!fs.existsSync('public/'+imgPathOfBus)){
        fs.mkdirSync('public/'+imgPathOfBus);
    }
    console.log(fs.existsSync('public/'+imgPathOfBus)+'-----------public/'+imgPathOfBus+req.files.file.name);
    gm(req.files.file.path).crop(coords[2], coords[3], coords[0], coords[1])
        .resize(320, 320)//强制此宽高缩放，不是1比1的话会拉伸，不加！号可保持纵横比
        .noProfile()
        .write('public/'+imgPathOfBus+'/'+req.files.file.name, function (err) {
            if (!err){
                fs.unlinkSync(req.files.file.path);//删除文件原
                var img = imgPathOfBus+'/'+req.files.file.name;//获取新图片路径
                new LifeGoods(req.body.gname,req.body.price,req.body.describe,
                    req.body.lid,req.body.syid,img,new Date()).save(function(result){
                    res.setHeader('Content-Type','text/html');
                    res.send(result);
                });
            }
        });

});

/**
 * 编辑产品
 */
router.post('/auth/lifeService/editBusGoods', function(req,res){
    console.log(req.body.coords+'---------'+req.body.img);
    var img='public/'+req.body.img;
    if(req.files.file){//判断图片需不需要更新
        var coords = req.body.coords;
        var imgPathOfBus = 'images/busimgs/bus'+req.body.lid;//根据产品ID创建目录
        if(!fs.existsSync('public/'+imgPathOfBus)){
            fs.mkdirSync('public/'+imgPathOfBus);
        }
        console.log(fs.existsSync('public/'+imgPathOfBus)+'-----------public/'+imgPathOfBus+req.files.file.name);
        gm(req.files.file.path).crop(coords[2], coords[3], coords[0], coords[1])
            .resize(320, 320)//强制此宽高缩放，不是1比1的话会拉伸，不加！号可保持纵横比
            .noProfile()
            .write('public/'+imgPathOfBus+'/'+req.files.file.name, function (err) {
                if (!err){
                    fs.unlinkSync(req.files.file.path);//删除文件原
                    fs.unlinkSync(img);//删除原来的图片
                    img = imgPathOfBus+'/'+req.files.file.name;//获取新图片路径
                    goodsUodate(req, res, img);
                }
            });
    }else{
        goodsUodate(req, res, req.body.img);
    }
});

/**
 * 删除选中的商品
 */
router.post('/auth/lifeService/delBusGoods', function(req,res){
    var ids = req.body['ids'];
    new LifeGoods().delBusGoods(ids,function(result){
        res.send(result);
    });
});

/**
 * 修改订单状态
 */
router.post('/auth/lifeService/updateStatus', function(req,res){
    var ids = req.body.gid;
    new LifeGoods().updateStatus(ids,function(result){
        res.send(result);
    });
});

router.post('/auth/lifeService/GoodsOrdersList', function(req, res) {
    var params = [req.body.orDate1,req.body.orDate2,req.body.phone];
    var userid;
    if(req.session.passport.user.usertype==2){
        userid = req.session.passport.user.id;
    }

    var lid = req.query.lid;
    var page = [req.body.sort,req.body.order,(Number(req.body.page)-1)*Number(req.body.rows),Number(req.body.rows)];
    new LifeGoods().getOrderListOfLid(params,page,userid,lid,function(result){
        res.send(result);
    });
    debug('订单列表');

});

/**
 * 更新产品信息
 * @param req
 * @param res
 * @param img
 */
function goodsUodate(req, res, img){
    var lifeGoods = new LifeGoods(req.body.gname,req.body.price,req.body.describe,
        Number(req.body.lid),Number(req.body.syid),img,new Date(req.body.createtime));
    lifeGoods.gid = req.body.gid;
    lifeGoods.update(function(result){
        res.setHeader('Content-Type','text/html');
        res.send(result);
    });
}

router.post('/auth/lifeService/subscribe', function(req,res){
    var gid = req.body.gid;
    var userid = req.session.passport.user.id;
    new UserLifeGoods(userid,gid,0,new Date()).save(function(result){
        res.send(result);
    });
});

router.post('/registerUser', function(req,res){
    var phone = req.body.phone;
    var password = crypto.createHash('md5').update(req.body.password).digest('hex').toUpperCase();
    var modelnum = req.body.modelnum;//汽车型号
    var carnum = req.body.carnum;//车牌号
    var date = req.body.date;//保险到期日期
    //先查询手机是否已被注册
    new Users().checkUser(phone,function(result){
        if(result!='hasUser'&&result){
            new Users(phone,password,new Date(),modelnum,carnum,new Date(date),3).save(function(result){
                res.send(result);
            });
        }else{
            res.send(result);
        }

    });
});


router.post('/getCode', function(req,res){
    var randomNum = randomString({
        length: 6,
        numeric: true,
        letters: false,
        special: false
    });
    console.log(req.body.phone+' '+req.body.msg+' '+randomNum);// req.body.msg+',验证码：'+randomNum
    luosimao.sms(req.body.phone,req.body.msg+',验证码：'+randomNum+'【立众车友汇】');

    res.send(randomNum);
});

router.post('/sendMsg', function(req,res){

    //console.log(req.body.phone+' '+req.body.msg+' '+randomNum);// req.body.msg+',验证码：'+randomNum
    luosimao.sms(req.body.phone,req.body.msg+'【立众车友汇】');

    res.send(true);
});

/*router.post('/pay/notify', function(req,res){

    var buf = new BufferHelper();
    buf.load(req, function(err, buf) {
        if (err) {
            debug("req body:", req.body);
        } else {
            var xml = buf.toString('utf-8');
            xml2js.parseString(xml, {
                trim: true
            }, function(e, r) {
                debug("xml2js result:", r);
            });

            console.log(req.body+'-----'+req.body.body);
            res.send('success');
        }
    });
});*/


module.exports = router;
